import axios from 'axios';
import { util } from '../common/util';
import vm from '../main';
import { config } from '../config';
import { store } from "../store/index.js";

// axios 全局配置
axios.defaults.timeout = 20000;
axios.defaults.baseURL = store.getters.getDebugSetting.APIPath; //这是调用数据接口
//axios.defaults.headers = {//设置跨域头部
  //'Content-Type':'application/x-www-form-urlencoded' 
//}

// http request 拦截器
/* axios.interceptors.request.use(
  config => {
    //if(debugSetting.display) console.log(config.data)
    config.headers = {
      //...
    };
    return config;
  },
  err => {
    return Promise.reject(err);
  }
); */

// http response 拦截器
/* axios.interceptors.response.use(
  response => {
    if(response.data.status == 'timeout'//response.data.status是我接口返回的值，如果值为timeout
    && location.hash.indexOf('password') < 0//设置某些特别的页面不会跳转
    ) {
      router.push({
          path: '/login',
          query: {redirect: router.currentRoute.fullPath}  //从哪个页面跳转
      })
    };
    return response;
  },
  error => {
    return Promise.reject(error.response.data)
  }
); */

export const request = {
  // post方法
  post: function (url, params, callback, needSuccess = true) {
    let axiosIns = axios.create({
      headers: {
        "token": store.getters.getToken
      }
    });
    vm.$store.commit('updateAppLoading', {appLoading: true});
    axiosIns.post(url, params)
    .then(res => {
      vm.$store.commit('updateAppLoading', {appLoading: false});
      let {code: status, msg: msg, data: data, ...rest} = res.data;
      if(store.getters.getDebugSetting.display) 
        console.log({status, msg, data, rest});
      if(status != 0){ // 验证服务器端自定义的错误状态
        vm.$UIplugins.message({message: msg, type: 'error'});
        if(status == 404) loginOut(); // 服务器端判断为token过期情况
        if(needSuccess) return;
      }
      callback({status, msg, data, rest});
    })
    .catch((err) => {
      if(store.getters.getDebugSetting.display)
        console.log(`${url} axios post err: \n ${JSON.stringify(err)}`);
      if(err && err.response) showError(err.response);
      else if(err && err.message) showError(err.message);
      vm.$store.commit('updateAppLoading', {appLoading: false});
    })
  },
  // get方法
  get:function (url, callback, needSuccess = true) {
    let axiosIns = axios.create({
      headers: {
        "token": store.getters.getToken
      }
    });
    vm.$store.commit('updateAppLoading', {appLoading: true});
    axiosIns.get(url)
    .then((res) => {
      vm.$store.commit('updateAppLoading', {appLoading: false});
      let {code: status, msg: msg, data: data, ...rest} = res.data;
      if(store.getters.getDebugSetting.display) 
        console.log({status, msg, data, rest});
      if(status != 0){ // 验证服务器端自定义的错误状态
        vm.$UIplugins.message({message: msg, type: 'error'});
        if(status == 404) loginOut(); // 服务器端判断为token过期情况
        if(needSuccess) return;
      }
      callback({status, msg, data, rest});
    })
    .catch((err) => {
      if(store.getters.getDebugSetting.display)
        console.log(`${url} axios post err: \n ${JSON.stringify(err)}`);
      if(err && err.response) showError(err.response);
      else if(err && err.message) showError(err.message);
      vm.$store.commit('updateAppLoading', {appLoading: false});
    })
  },
  // upload方法
  upload: async function (files, callback, options, needSuccess = true) {
    let axiosIns = axios.create({
      headers: {
        //'Content-Type': 'multipart/form-data',
        "token": store.getters.getToken
      },
    });
    let formData = new FormData(); // FormData对象
    if(!(files instanceof Array)) 
      files = new Array(files); // 判断传过来的是不是数组
    for(var i = 0; i < files.length; i++){
      let convertFile = 
        options.compress ? 
        await util.uploadSectionFile(files[i].file, options) : 
        files[i].file;
      formData.append('file', convertFile);
    }
    vm.$store.commit('updateAppLoading', {appLoading: true});
    axiosIns.post('uploadFiles', formData)
    .then(res => {
      vm.$store.commit('updateAppLoading', {appLoading: false});
      let {code: status, msg: msg, data: data, ...rest} = res.data;
      if(store.getters.getDebugSetting.display) 
        console.log({status, msg, data, rest});
      if(status != 0){ // 验证服务器端自定义的错误状态
        vm.$UIplugins.message({message: msg, type: 'error'});
        if(status == 404) loginOut(); // 服务器端判断为token过期情况
        if(needSuccess) return;
      }
      callback({status, msg, data, rest});
    })
    .catch((err) => {
      if(store.getters.getDebugSetting.display)
        console.log(`${url} axios post err: \n ${JSON.stringify(err)}`);
      if(err && err.response) showError(err.response);
      else if(err && err.message) showError(err.message);
      vm.$store.commit('updateAppLoading', {appLoading: false});
    })
  },
} 

const loginOut = () => { // 登出系统
  util.delLocalStorage('token_' + config.appName);
  util.delLocalStorage('userInfo_' + config.appName);
  vm.$router.push({
      path: '/login',
      query: {redirect: vm.$router.currentRoute.fullPath}  //从哪个页面跳转
  })
};

const showError = error => { // http状态码显示错误提示
	let errorMsg = ''
	if(typeof error == 'string') errorMsg = error;
	else
    switch (error.status) {
      case 400:
        errorMsg = '请求参数错误'
        break
      case 401:
        errorMsg = '未授权，请登录'
        break
      case 403:
        errorMsg = '跨域拒绝访问'
        break
      case 404:
        errorMsg = '请求地址出错'
        break
      case 408:
        errorMsg = '请求超时'
        break
      case 500:
        errorMsg = '服务器内部错误'
        break
      case 501:
        errorMsg = '服务未实现'
        break
      case 502:
        errorMsg = '网关错误'
        break
      case 503:
        errorMsg = '服务不可用'
        break
      case 504:
        errorMsg = '网关超时'
        break
      case 505:
        errorMsg = 'HTTP版本不受支持'
        break
      default:
        errorMsg = error.msg
        break
    };
  vm.$UIplugins.message({message: errorMsg, type: 'error'});
}

// 导出api方法对象
export const api = {};
// 获取当前文件夹下的js文件列表并赋值api对象
const files = require.context('.', false, /\.js$/);
files.keys().forEach(key => {
  if(key.indexOf('index') < 0){
    api[key.replace('./', '').replace('_api.js', '')] = files(key).default;
  }
});
/*
import { info } from './info_api';
import { user } from './user_api';
import { other } from './other_api';

export const api = {
  info,
  user,
  other
};*/
